<template>
  <el-dialog v-model="cameraDialogVisible" title="人脸识别" width="500px" :close-on-click-modal="false">
    <div class="camera-container">
      <video ref="videoElement" class="camera-video" autoplay></video>
      <canvas ref="canvasElement" class="camera-canvas"></canvas>
      <div class="camera-buttons">
        <el-button type="primary" @click="captureImage">拍照</el-button>
        <el-button type="success" @click="uploadImage" :loading="isUploading">上传识别</el-button>
      </div>
    </div>
  </el-dialog>
  <div class="user-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <!-- 系统logo -->
      <div class="logo">
        <img src="@/logo/1.png" alt="系统logo" class="logo-img" @click="cameraDialogVisible = true">
      </div>
      <!-- 导航菜单 - 添加AI聊天链接 -->
      <div class="top-nav">
        <router-link to="/user-home/DeviceQuery" class="nav-item" active-class="active">设备管理</router-link>
        <router-link to="/user-home/ai-chat" class="nav-item" active-class="active">AI聊天</router-link>
      </div>

      <!-- 操作图标区域 -->
      <div class="header-actions">
        <router-link to="/user-home"><el-icon class="icon">
            <User />
          </el-icon></router-link>
        <router-link to="/login"><el-icon class="icon">
            <CircleClose />
          </el-icon></router-link>
      </div>
    </el-header>

    <!-- 主内容区域 -->
    <el-main class="content-area">
      <div class="content-wrapper" v-show="$route.path === '/user-home'">
        <!-- 仅在访问/user-home根路径时显示主页内容 -->
        <div>
          <!-- 整体布局：左侧2列 + 右侧1列 -->
          <el-row :gutter="20" class="main-content-layout">
            <!-- 左侧区域（占2/3宽度） -->
            <el-col :span="16">
              <!-- 统计卡片区域 -->
              <el-row :gutter="20" class="stat-cards">
                <el-col :span="10">
                  <el-card class="stat-card">
                    <div class="card-content">
                      <div class="card-title">总设备数</div>
                      <div class="card-value">{{ loading ? '加载中...' : totalDevices }}</div>
                      <div class="card-trend"></div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <!-- 图表区域 -->
              <div class="chart-container">
                <el-card class="chart-card">
                  <div slot="header" class="card-header">
                    <span>设备状态分布</span>
                  </div>
                  <div id="deviceStatusChart" class="chart-content"></div>
                </el-card>
              </div>
            </el-col>

            <!-- 右侧区域（占1/3宽度） -->
            <el-col :span="8" class="right-column" style="height: 100%;">
              <el-card class="url-card" style="height: 100%;">
                <div slot="header" class="card-header">
                </div>
                <div class="url-content">
                  <iframe :src="'https://127.0.0.1:3001/broadcastingAvatar.html'" class="content-iframe"></iframe>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="chart-container">

        </div>
      </div>

      <!-- 子路由视图 - 仅在访问子路径时显示 -->
      <router-view v-show="$route.path.startsWith('/user-home/')" />

      <!-- 删除设备查询组件 -->
      <!-- DeviceQuery /-->

    </el-main>
  </div>
</template>

<script>
import { User, CircleClose, Camera } from '@element-plus/icons-vue';
import { ElHeader, ElMain, ElRow, ElCol, ElCard, ElDialog, ElButton } from 'element-plus';
import { onMounted, onUnmounted, ref, watch, onActivated, nextTick } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import DeviceQuery from './DeviceQuery.vue';
import * as echarts from 'echarts';
import { useRoute } from 'vue-router';
// 删除下面这行重复的导入
// import request from '@/utils/request';

export default {
  name: 'UserHome',
  components: {
    ElHeader, ElMain, ElRow, ElCol, ElCard,
    User, CircleClose, DeviceQuery
  },
  setup() {
    const route = useRoute();
    const chartInstance = ref(null);
    const forceReinit = ref(false);
    const cameraDialogVisible = ref(false);
    const videoElement = ref(null);
    const canvasElement = ref(null);
    const capturedImage = ref(null);
    const isUploading = ref(false);
    const streamRef = ref(null);
    // ... existing code ...


    // 打开摄像头
    const openCamera = async () => {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({
            video: { width: 400, height: 300 },
            audio: false
          });
          streamRef.value = stream;
          videoElement.value.srcObject = stream;
        } catch (error) {
          ElMessage.error('无法访问摄像头，请确保已授予权限');
          console.error('摄像头访问错误:', error);
        }
      } else {
        ElMessage.error('您的浏览器不支持摄像头功能');
      }
    };

    // 关闭摄像头
    const closeCamera = () => {
      if (streamRef.value) {
        streamRef.value.getTracks().forEach(track => track.stop());
      }
    };

    // 拍照
    const captureImage = () => {
      const canvas = canvasElement.value;
      const video = videoElement.value;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
      capturedImage.value = canvas.toDataURL('image/jpeg');
      // 隐藏视频，显示照片
      video.style.display = 'none';
      canvas.style.display = 'block';
    };

    // 上传图像
    const uploadImage = async () => {
      if (!capturedImage.value) {
        ElMessage.warning('请先拍照');
        return;
      }

      isUploading.value = true;
      try {
        // 将base64转换为Blob
        const response = await fetch(capturedImage.value);
        const blob = await response.blob();
        const file = new File([blob], 'face.jpg', { type: 'image/jpeg' });

        // 创建FormData
        const formData = new FormData();
        formData.append('file', file);

        // 上传到接口
        const res = await request.post('/users/face', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          // 添加超时设置
          timeout: 30000  // 30秒超时
        });

        // 修复：添加响应存在性检查
        if (!res) {
          throw new Error('API未返回响应');
        }

        // 修复：检查data存在性并支持多种响应格式
        const responseData = res.data || res;
        // 修改状态码验证逻辑以匹配后端实际返回
        // 添加调试日志查看完整响应数据
        console.log('人脸识别响应数据:', responseData);
        // 修复：更灵活的状态码获取方式
        const code = responseData.code ?? res.code ?? res.status;
        if (code === 200) {
          ElMessage.success('人脸识别成功');
          cameraDialogVisible.value = false;
          // 添加调试日志
          console.log('准备跳转至:', 'https://cloudrendering.unity.cn/share/6f27306c729fd336');
          // 使用setTimeout确保对话框关闭后再跳转
          setTimeout(() => {
            window.location.href = 'https://cloudrendering.unity.cn/share/6f27306c729fd336';
          }, 500);
        } else {
          ElMessage.error(`识别失败: ${responseData.msg || res.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('上传失败:', error);
        // 详细错误分类提示
        if (error.message.includes('timeout')) {
          ElMessage.error('请求超时，请检查网络连接');
        } else if (error.message.includes('API未返回响应')) {
          ElMessage.error('服务器无响应，请联系管理员');
        } else if (error.response) {
          ElMessage.error(`上传失败: ${error.response.status} ${error.response.statusText}`);
        } else {
          ElMessage.error('上传失败，请重试');
        }
      } finally {
        isUploading.value = false;
      }
    };

    // 监听弹窗显示状态
    watch(cameraDialogVisible, (visible) => {
      if (visible) {
        openCamera();
      } else {
        closeCamera();
        // 重置摄像头和画布状态
        if (videoElement.value) videoElement.value.style.display = 'block';
        if (canvasElement.value) {
          canvasElement.value.style.display = 'none';
          canvasElement.value.getContext('2d').clearRect(0, 0, canvasElement.value.width, canvasElement.value.height);
        }
        capturedImage.value = null;
      }
    });



    // 添加设备统计数据响应式变量
    const deviceData = ref([]);
    const totalDevices = ref(0);
    const onlineDevices = ref(0);
    const alarmDevices = ref(0);
    // 添加设备类型统计数据
    const deviceTypesData = ref([]);
    const loading = ref(false);

    // 修改图表配置为动态数据
    const option = {
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      // 添加自定义颜色配置
      color: ['#1890ff', '#52c41a', '#faad14'],
      legend: {
        top: 'bottom',  // 图例位置调整到底部
        left: 'center',
        orient: 'horizontal',  // 水平布局
        itemWidth: 12,  // 图例标记大小
        itemHeight: 12,
        textStyle: { fontSize: 12 }
      },
      series: [{
        name: '设备状态',  // 修改图表名称为设备状态
        type: 'pie',
        radius: ['30%', '60%'],  // 调整环形比例
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 4,  // 减小圆角
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {  // 修改中心标签配置
          show: false,  // 默认隐藏中心标签
          position: 'center',
          formatter: '{b}: {c} ({d}%)',
          rich: {
            total: { fontSize: 20, fontWeight: 'bold' },
            name: { fontSize: 12, color: '#666' }
          }
        },
        emphasis: {
          label: {
            show: true,  // 鼠标悬停时显示中心标签
            fontSize: 16
          }
        },
        labelLine: { show: false },
        data: deviceTypesData.value  // 保持原有数据来源
      }]
    };

    // 添加设备数据获取和统计函数
    const fetchDeviceStats = async () => {
      loading.value = true;
      try {
        // 删除动态import，直接使用已导入的request
        const response = await request.get('/equipment/getAllEquipment');

        console.log('完整API响应:', response); // 添加详细日志

        // 修复状态码判断逻辑
        if ((response.code === 200) && Array.isArray(response.data)) {
          deviceData.value = response.data;

          // 添加设备名称统计逻辑
          const typeCounts = {};
          deviceData.value.forEach(device => {
            const deviceName = device.equipmentName;
            if (deviceName) {
              typeCounts[deviceName] = (typeCounts[deviceName] || 0) + 1;
            }
          });

          // 转换为ECharts所需格式
          deviceTypesData.value = Object.entries(typeCounts)
            .map(([name, value]) => ({ name, value }))
            .sort((a, b) => b.value - a.value);

          // 添加数据验证日志
          console.log('图表数据:', deviceTypesData.value);
          if (deviceTypesData.value.length === 0) {
            ElMessage.warning('没有找到设备名称数据，请检查API响应');
          }

          // 添加图表刷新逻辑
          nextTick(() => reuseChartInstance());

          // 新增总设备数统计
          totalDevices.value = deviceData.value.length;

          // 保留原有的状态统计用于卡片显示
          onlineDevices.value = deviceData.value.filter(d =>
            d.status === 'online' || d.status === 1 || d.status === '正常'
          ).length;
        } else {
          ElMessage.warning(`获取设备数据失败: ${response?.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('设备数据获取失败:', error);
        ElMessage.error('获取设备数据失败，请检查网络连接');
      } finally {
        loading.value = false;
      }
    };

    // 修改初始化函数
    const initChart = async () => {
      try {
        // 确保数据已加载
        if (deviceTypesData.value.length === 0) {
          console.log('数据尚未加载，等待数据...');
          // 数据未加载时等待并重试
          await new Promise(resolve => setTimeout(resolve, 500));
          return initChart(); // 递归重试
        }

        const chartDom = document.getElementById('deviceStatusChart');
        if (!chartDom) {
          console.error('图表容器不存在');
          return;
        }

        // 确保实例化前销毁旧实例
        if (chartInstance.value) {
          chartInstance.value.dispose();
        }

        chartInstance.value = echarts.init(chartDom);
        // 直接使用响应式数据
        const chartOption = {
          ...option,
          series: [{
            ...option.series[0],
            data: deviceTypesData.value
          }]
        };
        chartInstance.value.setOption(chartOption);

        // 添加窗口大小变化监听
        window.addEventListener('resize', () => {
          chartInstance.value?.resize();
        });
      } catch (error) {
        console.error('图表初始化失败:', error);
      }
    };

    // 添加深度刷新函数
    const reuseChartInstance = () => {
      const chartDom = document.getElementById('deviceStatusChart');
      if (chartInstance.value && chartDom) {
        console.log('执行深度刷新，数据:', deviceTypesData.value);

        // 阶段1：强制更新容器尺寸
        chartDom.style.height = `${Math.max(chartDom.clientHeight, 400)}px`;

        // 阶段2：清除可能残留的动画
        chartInstance.value.clear();

        // 阶段3：重新应用配置
        // 显式更新图表数据
        const updatedOption = { ...option };
        updatedOption.series[0].data = deviceTypesData.value || [];
        chartInstance.value.setOption(updatedOption, true); // 使用notMerge模式

        // 阶段4：触发复合刷新
        chartInstance.value.resize({
          animation: {
            duration: 300
          }
        });

        // 添加数据验证
        if (!deviceTypesData.value || deviceTypesData.value.length === 0) {
          console.error('图表数据为空');
          ElMessage.warning('图表数据为空，请检查数据来源');
        }

        // 阶段5：强制重绘
        chartInstance.value.dispatchAction({ type: 'hideTip' });
        chartInstance.value.dispatchAction({ type: 'showTip' });
      } else {
        console.error('图表实例或容器不存在');
        // 尝试重新初始化
        if (chartDom) initChart();
      }
    };

    // 处理链接点击
    const handleLinkClick = () => {
      console.log('跳转到Unity云渲染页面');
    };

    // 页面加载和窗口大小变化时初始化图表
    onMounted(() => {
      console.log('组件挂载 - 开始获取数据');
      // 移除原有的fetchDeviceStats调用

      const handleResize = () => chartInstance.value?.resize();
      window.addEventListener('resize', handleResize);

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
      });
    });

    // 添加路由监听
    watch(() => route.path, (newPath) => {
      if (newPath === '/user-home') {
        console.log('路由切换到主页 - 重新加载数据和图表');
        fetchDeviceStats().then(() => {
          nextTick(() => initChart());
        });
      } else if (chartInstance.value) {
        console.log('离开主页 - 销毁图表实例');
        chartInstance.value.dispose();
        chartInstance.value = null;
      }
    }, { immediate: true });

    // 页面卸载时销毁图表
    onUnmounted(() => {
      window.removeEventListener('resize', initChart);
      if (chartInstance.value) {
        chartInstance.value.dispose();
        chartInstance.value = null;
      }
    });

    // 添加路由激活处理
    onActivated(() => {
      console.log('路由激活-强制重新初始化图表');
      forceReinit.value = true;
      initChart();

      // 使用IntersectionObserver监听元素可见性
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            console.log('容器进入可视区域');
            reuseChartInstance();
            observer.unobserve(entry.target);
          }
        });
      });

      const chartDom = document.getElementById('deviceStatusChart');
      if (chartDom) {
        observer.observe(chartDom);
      }

      // 500ms超时保障
      setTimeout(() => {
        reuseChartInstance();
      }, 500);
    });
    // 修复变量导出 - 添加所有需要在模板中使用的响应式变量
    return {
      handleLinkClick,
      totalDevices,
      onlineDevices,
      alarmDevices,
      loading,
      deviceTypesData,
      cameraDialogVisible,
      videoElement,
      canvasElement,
      capturedImage,
      isUploading,
      streamRef,
      captureImage,
      uploadImage,
      isUploading
    };
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.user-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #e9e9e9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  height: 40px;
  width: auto;
  object-fit: contain;
}

.top-nav {
  display: flex;
  flex: 1;
  margin: 0 20px;
  height: 100%;
}

.nav-item {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #333;
  font-size: 14px;
  font-weight: 500;
  position: relative;
}

.nav-item.active {
  background-color: #dcdcdc;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #409EFF;
}

.header-actions {
  display: flex;
  gap: 20px;
}

.icon {
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.icon:hover {
  color: #409EFF;
}

.content-area {
  flex: 1;
  background-color: white;
  padding: 10px;
  /* 从20px减少到10px */
  overflow: auto;
}

.content-wrapper {
  width: 100%;
  height: 100%;
}

.main-content-layout {
  margin-top: 0;
  /* 从20px改为0 */
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 150px;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
}

.card-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-trend {
  display: flex;
  align-items: center;
}

.trend-up {
  color: #52c41a;
  margin-right: 5px;
}

.trend-down {
  color: #f5222d;
  margin-right: 5px;
}

.trend-text {
  color: #909399;
  font-size: 12px;
}

/* 新增图表样式 */
.chart-container {
  margin-bottom: 20px;
}

/* 修改图表容器样式 */
.chart-card {
  height: 100%;
  /* 将固定高度改为100%以匹配右侧列高度 */
  min-height: 500px;
  /* 保留最小高度确保内容正常显示 */
  /* 增加卡片高度以适应内容 */
}

/* 新增flex容器样式 */
.chart-content-container {
  display: flex;
  width: 100%;
  height: calc(100% - 40px);
  gap: 15px;
}

/* 删除重复的宽度设置 */
/* 调整图表区域样式 */
.chart-content {
  /* width: 60%; 删除重复的宽度设置 */
  height: 100%;
  min-height: 400px;
}

/* 新增外部内容区域样式 - 已由右侧卡片布局替代 */
/* .external-content {
  width: 40%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
} */

/* URL内容容器样式 */
.url-content {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  flex: 1;
  display: flex;
}

/* iframe样式 */
.content-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

/* 卡片样式确保没有内边距 */
.right-card .el-card__body {
  padding: 0 !important;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.url-content {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.content-iframe {
  width: 100%;
  flex: 1;
  border: none;
}

/* 确保父容器高度继承 */
.main-content-layout {
  height: calc(100vh - 180px);
}

.right-column {
  display: flex;
  /* 添加flex布局确保高度正确传递 */
  flex-direction: column;
  height: 100%;
}

:deep(.el-card__body) {
  padding: 15px;
  height: 100%;
  box-sizing: border-box;
}

.camera-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 350px;
  /* 添加固定高度 */
  position: relative;
  /* 添加相对定位 */
}

.camera-video,
.camera-canvas {
  width: 400px;
  height: 300px;
  border: 1px solid #eee;
  object-fit: cover;
  margin-bottom: 20px;
}

.camera-canvas {
  display: none;
  /* 修改绝对定位为相对定位 */
  position: relative;
  top: auto;
  /* 移除top定位 */
}

.camera-buttons {
  display: flex;
  gap: 10px;
}
</style>

<!-- 新增摄像头弹窗 -->
